#include "rknnthread.h"




#include <QCoreApplication>
#include <QDebug>

#include "rkYolov5s.hpp"


RknnThread::RknnThread(QObject *parent,int nCoreNum)
{
   int i = 0;
   m_AppPath = QCoreApplication::applicationDirPath();

   m_NpuCore = nCoreNum;
   m_parent = parent;
   m_nFps = 0;
   m_ThreadRun = true;
}


RknnThread::~RknnThread()
{
    int i;

    printf("~RknnThread()");
}

void RknnThread::run()
{
    int  i = 0;
    int  nReadLen = 0;
    int  nRes = 0;

    unsigned char  cBuff[1024*1024] = {0};
    std::string  modePath = m_AppPath.toStdString() + "/model/RK3588/yolov5s-640-640.rknn";

    int   nPts = 0;
    rknn_context  curCtx;
    rkYolov5s*  pYoloInst = new rkYolov5s(modePath);
    nRes = pYoloInst->init(&curCtx,false,m_NpuCore);
    if(nRes < 0)
    {
        qDebug() << "yolo init failure " << modePath.c_str();
    }
    else
    {
        qDebug() << "yolo init npu core " << m_NpuCore << "success" << endl;
    }


    std::string  image_name = m_AppPath.toStdString() + "/bus.jpg";
    cv::Mat orig_img = cv::imread(image_name, 1);
    if (!orig_img.data)
    {
         printf("cv::imread %s fail!\n", image_name.c_str());
         return ;
     }

    cv::Mat img = orig_img.clone();
    cv::cvtColor(orig_img, img, cv::COLOR_BGR2RGB);

    while(m_ThreadRun)
    {
         int nObjCnt = 0;
         pYoloInst->infer(img,nObjCnt);
         //printf("yolo %d detect %d object !\n",m_NpuCore,nObjCnt);
         m_nFps++;
    }
    delete pYoloInst;
    printf("RknnThread %d will exit !\n",m_NpuCore);
}

void RknnThread::Stop()
{
    m_ThreadRun = 0;
}


